// pages/chatroom/chatroom.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    petID: '',
    roomId: '',
    chats: [],
    messages: [],
    petDetail: null,
    value: '',
    scrollIntoViewId: '', // 用于滚动到指定元素的 ID

    usType: 'user'
  },

  /**
   * 页面加载时创建 WebSocket 连接
   */
  onLoad(options) {

    this.setData({
      petID: options.petId,
      roomId: options.roomId,
      usType: wx.getStorageSync('user').usertype
    })
    this.connectWebSocket();
    wx.request({
      method: "POST",
      data: {
        roomId: this.data.roomId,
        chatsList: [{
          url: 'http://localhost:3000/work-2.jpg',
          info: '你好',
          user: '67767f17e1006c39f3902ae1'
        }]
      },
      url: 'http://localhost:3000/api/addchats',
      success: (res) => {
        console.log(res.data);
        this.getChats()
        this.getPet()
      }
    })

  },

  /**
   * 页面卸载时关闭 WebSocket 连接
   */
  onUnload() {
    this.closeWebSocket();
  },

  /**
   * 创建 WebSocket 连接
   */
  async connectWebSocket() {
    this.socketTask = await wx.connectSocket({
      url: 'ws://localhost:3300', // 服务器地址
      success: (res) => {
        console.log('WebSocket 连接成功', res);
      },
      fail: (err) => {
        console.log('WebSocket 连接失败', err);
      }
    });

    // 监听连接打开事件
    this.socketTask.onOpen((res) => {
      console.log('WebSocket 连接已打开', res);
      // 客户端加入房间
      const joinMessage = JSON.stringify({
        type: 'message',
        action: 'join',
        roomId: this.data.roomId
      });
      //  ws.value.send(joinMessage);
      this.socketTask.send({
        data: joinMessage,
        success: (res) => {
          console.log('加入房间成功', res);
        },
        fail: (err) => {
          console.log('加入房间失败', err);
        }
      });
    });

    // 监听消息接收事件
    this.socketTask.onMessage((res) => {
      this.getChats()
    });

    // 监听连接关闭事件
    this.socketTask.onClose((res) => {
      console.log('WebSocket 连接已关闭', res);
    });

    // 监听错误事件
    this.socketTask.onError((err) => {
      console.log('WebSocket 连接错误', err);
    });
  },

  /**
   * 关闭 WebSocket 连接
   */
  closeWebSocket() {
    if (this.socketTask) {
      this.socketTask.close({
        success: (res) => {
          console.log('WebSocket 连接已关闭', res);
        },
        fail: (err) => {
          console.log('关闭 WebSocket 连接失败', err);
        }
      });
    }
  },

  /**
   * 发送消息
   */
  submit() {
    const message = this.data.value;
    if (message.trim() === '') {
      wx.showToast({
        title: '消息不能为空',
        icon: 'none'
      });
      return;
    }
    this.setData({
      chats: [...this.data.chats, {
        url: 'http://localhost:3000/bg9.jpg',
        info: message,
        user: this.data.roomId
      }],
      value: ''
    });

    if (this.socketTask) {
      this.socketTask.send({
        data: JSON.stringify({
          type: 'message',
          title: '消息发送',
          message: message,
          roomId: this.data.roomId
        }),
        success: (res) => {
          console.log('消息发送成功', res);
          this.updateChats()
          this.scrollToBottom()
        },
        fail: (err) => {
          console.log('消息发送失败', err);
        }
      });
    } else {
      wx.showToast({
        title: 'WebSocket 未连接',
        icon: 'none'
      });
    }
  },

  // 滚动到最新消息
  scrollToBottom() {
    // 获取消息列表的最后一个元素的 ID
    this.setData({
      scrollIntoViewId: 'msg-' + (this.data.chats?.length - 1)
    })
    console.log(this.data);
  },

  // 获取聊天信息
  getChats() {
    wx.request({
      data: {
        roomId: this.data.roomId,
      },
      url: 'http://localhost:3000/api/chats',
      success: (res) => {
        // console.log("消息列表", res.data.list[0].chatsList);
        this.setData({
          chats: res.data.list[0]?.chatsList,
          messages: res.data.list[0],
        })
        this.scrollToBottom()
      }
    })
  },
  // 获取宠物信息
  getPet() {
    wx.request({
      url: 'http://localhost:3000/api/pets',
      success: (res) => {
        this.setData({
          petDetail: res.data.findResAll.find(item => item._id == this.data.petID)
        })
        console.log("宠物", this.data.petDetail);
      }
    })
  },
  // 保存信息
  updateChats() {
    console.log(this.data.chats);
    wx.request({
      method: "POST",
      data: {
        roomId: this.data.roomId,
        chatsList: [...this.data.chats]
      },
      url: 'http://localhost:3000/api/updatechats',
      success: (res) => {
        console.log("发送成功", res.data);
        this.getChats()
      }
    })
  },
  send() {
    this.setData({
      value: '宠物信息：' + this.data.petDetail.name + ',' + this.data.petDetail.variety + ',' + this.data.petDetail.resource
    })
  }
});